<template>
  <div class="spu-list-page">
    <van-nav-bar title="商品列表" left-arrow @click-left="goBack" />
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索商品"
        @search="onSearch"
        @clear="onClear"
      />
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <van-dropdown-menu>
        <van-dropdown-item v-model="sortBy" :options="sortOptions" />
        <van-dropdown-item v-model="priceRange" :options="priceOptions" />
      </van-dropdown-menu>
    </div>
    
    <!-- 商品列表 -->
    <div class="spu-list">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadMore"
      >
        <div class="spu-grid">
          <spu-preview
            v-for="spu in spuList"
            :key="spu.id"
            :spu="spu"
            @click="goToDetail(spu.id)"
          />
        </div>
      </van-list>
    </div>
    
    <!-- 空状态 -->
    <van-empty v-if="spuList.length === 0 && !loading" description="暂无商品" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getSpuList, getSpuByCategory } from '@/api/home'
import SpuPreview from '@/components/spu-preview/index.vue'

const route = useRoute()
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const sortBy = ref('default')
const priceRange = ref('all')
const spuList = ref([])
const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = 10

// 排序选项
const sortOptions = [
  { text: '默认排序', value: 'default' },
  { text: '价格从低到高', value: 'price_asc' },
  { text: '价格从高到低', value: 'price_desc' },
  { text: '销量优先', value: 'sales' },
  { text: '最新上架', value: 'newest' }
]

// 价格区间选项
const priceOptions = [
  { text: '全部价格', value: 'all' },
  { text: '0-50元', value: '0-50' },
  { text: '50-100元', value: '50-100' },
  { text: '100-200元', value: '100-200' },
  { text: '200元以上', value: '200+' }
]

// 获取商品列表
const getSpuListData = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    console.log('获取商品列表，路由参数:', route.query)
    
    // 获取路由参数
    const cid = route.query.cid
    const type = route.query.type
    
    let data
    
    if (cid && type) {
      // 根据分类获取商品
      const isRoot = type === 'root_category'
      const currentPage = reset ? 0 : (page.value - 1) * pageSize
      
      console.log('调用分类商品API:', { cid, isRoot, start: currentPage, count: pageSize })
      
      data = await getSpuByCategory(cid, isRoot, currentPage, pageSize)
    } else {
      // 获取最新商品（默认情况）
      const params = {
        page: reset ? 1 : page.value,
        pageSize,
        keyword: searchKeyword.value,
        sort_by: sortBy.value,
        price_range: priceRange.value
      }
      
      data = await getSpuList(params)
    }
    
    console.log('商品列表API响应:', data)
    
    if (data && data.items) {
      if (reset) {
        spuList.value = data.items
        page.value = 2
      } else {
        spuList.value.push(...data.items)
        page.value++
      }
      
      if (data.items.length < pageSize) {
        finished.value = true
      }
    } else {
      finished.value = true
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    showToast('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  getSpuListData()
}

// 搜索
const onSearch = () => {
  resetList()
  getSpuListData(true)
}

// 清空搜索
const onClear = () => {
  resetList()
  getSpuListData(true)
}

// 重置列表
const resetList = () => {
  spuList.value = []
  page.value = 1
  finished.value = false
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 跳转到商品详情
const goToDetail = (spuId) => {
  router.push(`/detail/${spuId}`)
}

// 监听筛选条件变化
watch([sortBy, priceRange], () => {
  resetList()
  getSpuListData(true)
})

// 组件挂载时获取数据
onMounted(() => {
  getSpuListData(true)
})
</script>

<style lang="scss" scoped>
.spu-list-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  background: #fff;
  padding: 10px 0;
}

.filter-bar {
  background: #fff;
  margin-bottom: 10px;
}

.spu-list {
  .spu-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 10px;
  }
}
</style> 